<template>
  <el-dialog
    :title="'添加'+ titleText"
    :visible.sync="addParamDialog"
    width="50%"
    @close="addParamClose"
  >
    <el-form :model="addParamForm" :rules="addParamRules" ref="addParamRef" label-width="100px">
      <el-form-item :label="titleText" prop="attr_name">
        <el-input v-model="addParamForm.attr_name"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="addParamDialog = false">取 消</el-button>
      <el-button type="primary" @click="addParams">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
export default {
  props: {
    visible: {
      type: Boolean
    },
    activeName: {
      type: String
    },
    cateId: {
      type: Number
    }
  },
  data() {
    return {
      addParamDialog: false,
      addParamForm: {
        attr_name: ''
      },
      addParamRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    addParamClose() {
      this.$refs.addParamRef.resetFields()
    },
    addParams() {
      this.$refs.addParamRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addParamForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error('添加' + this.titleText + '失败')
        }
        this.addParamDialog = false
        this.$emit('addParamSuccess')
      })
    }
  },
  watch: {
    visible: function(val) {
      this.addParamDialog = val
    },
    addParamDialog: function(val) {
      this.$emit('update:visible', val)
    }
  },
  computed: {
    titleText: function() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>
<style lang="less" scoped>
</style>
